// 该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
//引入组件
import Login from '../views/Login'
import Violation from '../views/Violation'
import { CheckLogin } from '@/utils/login'
import getRoutes from './routes'
import {getUserRole} from '../api/role'

const routes = [
	{
		path: '/login',
		name: 'login',
		component: Login
	},
	{
		path: '/',
		name: 'home',
		component: () => import('@/views/Home'),
		// component:Index,
		redirect:'/welcome',
		children: [
			{
				path: '/welcome',
				component: Violation,
				meta: {
					title: '主页',
					icon: 'el-icon-s-home',
				},
			},
		]
	}
	// {
	// 	path: '/test',
	// 	name: 'test',
	// 	component: Test
	// }
]


//创建并暴露一个路由器
const router = new VueRouter({
	routes
})

router.onReady(async () => {
	console.log('强制刷新了 重新加载对应的路由');
	let userRoutes=window.localStorage.getItem('userroutes')
	if(!userRoutes) return 
	const role=await getUserRole()
	if(role){
		if (Array.isArray(role)){
			router.addRoute('home',getRoutes(role))
		}else{
			router.addRoute('home',getRoutes('superuser'))
		}
	}
})


//全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
router.beforeEach((to, from, next) => {
	if (to.name != 'login') { //判断是否需要鉴权
		if (CheckLogin()) {
			next()
		} else {
			router.replace({ name: 'login' })
		}
	} else {
		next()
	}
})

//全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to, from) => {
	window.localStorage.setItem('path', to.path)
	document.title = to.meta.title || '振涛教育教学管理平台'
})

export default router
